<template>
	<view>
		<view v-if="type === '1' || type === '2'" class="bg-white">
			<u--form :model="formData" ref="myForm" labelWidth="80">
				<u--textarea v-model="formData.notes" placeholder="请输入服务记录" :count="true" border="none"></u--textarea>
				<u-form-item borderBottom>
					<u-upload
						:fileList="fileList2"
						@afterRead="afterRead"
						@delete="deletePic"
						uploadIconColor="#e54d42"
						uploadIcon="play-circle"
						name="2"
						multiple
						:maxCount="1"
						accept="video"
					></u-upload>
				</u-form-item>
				<u-form-item borderBottom>
					<u-upload
						:fileList="fileList1"
						@afterRead="afterRead"
						@delete="deletePic"
						uploadIconColor="#e54d42"
						uploadIcon="photo"
						name="1"
						multiple
						:maxCount="10"
					></u-upload>
				</u-form-item>
				<u-form-item label="服务日期" prop="serviceTime" borderBottom @click="showTimePicker=true">
					<u-input v-model="formData.serviceTime" border="none" placeholder="请选择" disabled disabledColor="#fff" />
					<u-icon slot="right" name="arrow-right"/>
				</u-form-item>
				<u-form-item label="项目明细" :borderBottom="formData.items.length === 0?true:false">
					<view 
						class="flex justify-between align-center" 
						v-if="formData.items.length === 0" 
						@click="addOrderItems">
						<u-input border="none" placeholder="请添加" disabledColor="#fff" disabled />
						<u-icon name="arrow-right" color="#606266" size="16"/>
					</view>
					<view v-else>
						<view v-for="(pIm, pIx) in formData.items" :key="pIx">
							<view class="pb-20 border-b" :class="pIx > 0?'pt-20':''">
								<view class="flex justify-between align-center" @click="addOrderItems">
									<text>{{pIm.name}}</text>
									<view @click.stop="onDelItem(pIx)">
										<u-icon name="close-circle" size="20" color="#e54d42"></u-icon>
									</view>
								</view>
								<view class="mt-10">
									<text class="line-red">￥{{pIm.price}}</text>
									<text class="line-grey fsize-22 ml-30">x{{pIm.nums}}</text>
								</view>
							</view>
							<view>
								<view class="flex justify-between align-center border-b pt-20 pb-20" 
									@click="$u.route('/pages/selectPage/staff',{index: pIx, type: '1'})">
									<text v-if="pIm.staffId === 0" class="fsize-24 text-pla">请选择服务人员</text>
									<text v-else class="fsize-24">{{pIm.staffName}}</text>
									<u-icon name="arrow-right" color="#606266" size="16" />
								</view>
							</view>
						</view>
					</view>
				</u-form-item>
			</u--form>
			<view class="sumBtn">
				<u-tag text="确认添加" shape="circle" color="#fff" borderColor="#e54d42" bgColor="#e54d42" size="large" @click="submit"/>
			</view>
		</view>
		<view v-else>
			<view class="pl-30 pr-30">
				<view>{{formData.createTime}}</view>
				<view class="line-gray">
					<view class="mt-10">
						<text>服务项目: </text>
						<text v-for="(im,ix) in formData.items" :key="ix">
							{{im.projectName}}
							<text v-if="ix !== formData.items.length-1">,</text>
						</text>
					</view>
					<view class="mt-10">服务时间: {{formData.serviceTime.slice(0, 10)}}</view>
					<view class="mt-10">
						<text>服务人: </text>
						<text v-for="(im,ix) in formData.items" :key="ix">
							{{im.staffName}}
							<text v-if="ix !== formData.items.length-1">,</text>
						</text>
					</view>
					<view class="mt-10">记录内容: {{formData.notes}}</view>
				</view>
			</view>
			<view class="mt-30" v-if="formData.imgs.length > 0">
				<view class="line-gray ml-30">图片:</view>
				<view class="flex flex--wrap">
					<image 
						class="width-210 height-210 mt-30 ml-30 border-radius-10" 
						:src="item" 
						mode="aspectFit" 
						v-for="(item, index) in formData.imgs"
						:key="index"
						@click="onPreviewImg(index)">
					</image>
				</view>
			</view>
			<view class="padding-30" v-if="formData.video">
				<view class="line-gray">视频:</view>
				<view class="mt-30">
					<video 
						id="myVideo" 
						class="w-100"
						:src="formData.video"
						controls
					></video>
				</view>
			</view>
		</view>
		<u-datetime-picker
			:show="showTimePicker"
			v-model="datetime"
			mode="datetime"
			@cancel = "showTimePicker=false"
			@confirm="onConfirmDataTime"
		></u-datetime-picker>
		<u-toast ref="uToast" />
	</view>
</template>

<script>
	import getDateTime from '@/common/getDataTime.js'
	export default {
		data(){
			return {
				showTimePicker: false,
				datetime:'',
				type: '1', // 1 新增 2编辑 3查看
				id: null,
				formData:{
					userId: null,
					notes:'',
					images:'',
					imgs:[],
					items:[],
					video:'',
					serviceTime:getDateTime.dateTimeStr('y/m/d h:i'),
				},
				fileList1: [],
				fileList2:[],
			}
		},
		onLoad(opt) {
			this.type = opt.type
			this.formData.userId = opt.userId
			if(opt.type === '2'){
				this.id = opt.id
				uni.setNavigationBarTitle({
					title:'编辑服务日志'
				})
				this.getDetails()
			}else if(opt.type === '3'){
				this.id = opt.id
				uni.setNavigationBarTitle({
					title:'日志详情'
				})
				this.getDetails()
			}
			uni.$on('add-pct', obj => {
				this.formData.items = obj
			})
			uni.$on('select-staff', obj => {
				this.formData.items[obj.index].staffId = obj.id
				this.formData.items[obj.index].staffName = obj.nickName
			})
		},
		onUnload() {
			// 移除监听事件
			uni.$off('add-pct')
			uni.$off('add-staff')
		},
		methods: {
			getDetails(){
				this.$reqJsonPost('UserServiceNoteGetDetails', {id: this.id}).then(res=>{
					this.formData = res.data
					this.formData.imgs = res.data.images?res.data.images.split(','):[],
					this.fileList1 = res.data.images?res.data.images.split(',').map(im=>{
						return {url:im}
					}):[]
					this.fileList2 = res.data.video?[{url:res.data.video}]:[],
					this.formData.items = res.data.items.map(im=>{
						im.name = im.projectName,
						im.itemId = im.projectId
						return im
					})
				})
			},
			onDelItem(ix){
				this.formData.items.splice(ix, 1)
			},
			addOrderItems(){
				uni.$u.route('/pages/selectPage/project',{ items:JSON.stringify(this.formData.items),type: '2' })	
			},
			onConfirmDataTime(e){
				this.formData.appointmentTime = uni.$u.timeFormat(e.value, 'yyyy-mm-dd hh:MM')
				this.showTimePicker = false
			},
			// 删除图片 视频
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
				// console.log(event.name, this[`fileList${event.name}`])
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.$reqUpLoad(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result.fileUrl
					}))
					fileListLen++
				}
			},
			onPreviewImg(ix){
				uni.previewImage({
					urls: this.formData.imgs,
					current: ix
				})
			},
			// 提交
			submit() {
				if(this.formData.items.length > 0){
					const index = this.formData.items.findIndex(im=> uni.$u.test.isEmpty(im.staffId))
					if(index !== -1){
						this.$refs.uToast.show({ message:'请选择服务人员!' })
						return
					}
					if(uni.$u.test.isEmpty(this.formData.notes)){
						this.$refs.uToast.show({ message:'请输入服务记录!' })
						return
					}
					const SubmitData = {
						...this.formData,
						orderId: '0',
						video: this.fileList2.length !==0?this.fileList2[0].url:'',
						images: this.fileList1.length !==0?this.fileList1.map(im=>im.url).join(','):'',
						items: this.formData.items.map(im=>{
							return {
								orderId:'0',
								projectId: im.itemId,
								nums: im.nums,
								price: im.price,
								staffId: im.staffId
							}
						})
					}
					if(this.type === '1'){
						this.$reqJsonPost('UserServiceNoteDoCreate', SubmitData).then(res=>{
							this.$refs.uToast.show({ 
								message: res.msg,
								complete(){
									uni.$emit('uplist', 1)
									uni.navigateBack()
								}
							})
						})
					}else if(this.type === '2'){
						this.$reqJsonPost('UserServiceNoteDoEdit', {...SubmitData, orderId: this.id }).then(res=>{
							this.$refs.uToast.show({ 
								message: res.msg,
								complete(){
									uni.$emit('uplist', 1)
									uni.navigateBack()
								}
							})
						})
					}
				}else {
					this.$refs.uToast.show({ message:'请选择服务项目!' })
				}
			}
		}
	}
</script>

<style>
	page{
		background-color: #fff;
	}
</style>
<style lang="scss" scoped>
	.sumBtn{
		position: fixed;
		bottom: 200rpx;
		left: 50%;
		transform: translateX(-50%);
	}
</style>